local _ = require ("moses")

local regex = [[\d+]]

 -- 参数"o"是开启缓存必须的
 local m = ngx.re.match("hello, 1234,9394", regex,"o")

 if m then
     -- m[0] == "1234"
     ngx.say("match== " .. m[0])
  
 else
     if err then
         ngx.log(ngx.ERR, "error: ", err)
         return
     end

     ngx.say("match not found!")
 end

-- 当匹配成功时，返回一个 Lua 表 captures，其中 captures[0] 存储(整个模板)匹配出的完整子字符串，
-- captures[1] 存储第一个括号内的子模板匹配结果，captures[2] 存储第二个
local m, err = ngx.re.match("hello, 1234", "([0-9]+?)[0-9]+", "jo")
-- m[0] == "1234"
-- m[1] == "1"
 ngx.say("m[0]== " .. m[0])
 ngx.say("m[1]== " .. m[1])

-- 命名捕获
local m, err = ngx.re.match("hello, 1234", "([0-9])(?<remaining>[0-9]+)", "jo")
ngx.say("hello, 1234", "([0-9])(?<remaining>[0-9]+) \n")
 _.each(m, ngx.say)
 
 -- m[0] == "1234"
 -- m[1] == "1"
 -- m[2] == "234"
 -- m["remaining"] == "234"

local res = {}

local m, err = ngx.re.match("hello, world", "(world)|(hello)|(?<named>howdy)", "" , {} ,res)
ngx.say("hello, world", "(world)|(hello)|(?<named>howdy) \n")

 _.each(m, ngx.say)
 _.each(res, ngx.say)

 -- m[0] == "hello"
 -- m[1] == false
 -- m[2] == "hello"
 -- m[3] == false
 -- m["named"] == false